package com.huluobo.day11_im.chat.presenter;

import android.util.Log;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

public class ChatPresenter implements ChatContract.Presenter {
    public List<EMMessage> messages = new ArrayList<>();
    private ChatContract.View view;

    private static final int PAGE_SIZE = 10;

    public ChatPresenter(ChatContract.View view) {
        this.view = view;
    }

    @Override
    public void sendMessage(String content, String username) {
        EMMessage emMessage = EMMessage.createTextSendMessage(content, username);
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                view.onSendMessageSuccess();
            }

            @Override
            public void onError(int code, String error) {
                view.onSendMessageFailed(error);
            }
        });
        messages.add(emMessage);
        view.onStartSendMessage();
        EMClient.getInstance().chatManager().sendMessage(emMessage);
    }

    @Override
    public void addMessage(String username, List<EMMessage> messages) {
        //接收到的消息需要加入到当前的消息列表中
        this.messages.addAll(messages);

        //只要进入到聊天界面,就把对应username 的所有会话标记为已读
        EMConversation conversation =
                EMClient.getInstance().chatManager().getConversation(username);
        conversation.markAllMessagesAsRead();
    }

    @Override
    public void loadMessage(String username) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EMConversation conversation =
                        EMClient.getInstance().chatManager().getConversation(username);
                if (conversation != null) {
                    conversation.markAllMessagesAsRead();
                    messages.addAll(conversation.getAllMessages());
                    view.onMessageLoaded();
                }

            }
        }).start();
    }

    @Override
    public void loadMoreMessage(String username) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EMConversation conversation =
                        EMClient.getInstance().chatManager().getConversation(username);
                String startId = messages.get(0).getMsgId();//查询历史聊天记录的起始位置
                List<EMMessage> emMessages = conversation.loadMoreMsgFromDB(startId, PAGE_SIZE);
                messages.addAll(0, emMessages);//加载历史聊天记录时,不能从list的末尾添加,需要从list的头部进行添加,
                // index=0的位置,这样禅城的聊天记录,才会符合逻辑
                view.onMoreMessageLoaded(emMessages.size());
            }
        }).start();
    }
}
